{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/data0/users/tanganke/anaconda3/envs/s2_moe/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from accelerate import init_empty_weights\n",
    "from transformers import AutoConfig\n",
    "\n",
    "from fusion_bench.models.modeling_s2_moe_llama import (\n",
    "    S2MoELlamaConfig,\n",
    "    S2MoELlamaForCausalLM,\n",
    ")\n",
    "\n",
    "MODEL_PATH = \"meta-llama/Llama-3.2-3B-Instruct\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = AutoConfig.from_pretrained(MODEL_PATH)\n",
    "config = S2MoELlamaConfig(\n",
    "    num_experts_per_tok=1,\n",
    "    rank_of_router=16,\n",
    "    num_local_experts=5,\n",
    "    use_sparse_expert=True,  # TODO\n",
    "    sparsity_ratio=0.8,  # ?\n",
    "    **config.to_dict(),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "S2MoELlamaForCausalLM(\n",
       "  (model): S2MoELlamaModel(\n",
       "    (embed_tokens): Embedding(128256, 3072)\n",
       "    (layers): ModuleList(\n",
       "      (0-27): 28 x S2MoELlamaDecoderLayer(\n",
       "        (self_attn): S2MoELlamaAttention(\n",
       "          (q_proj): SingularMoELinear(in_features=3072, out_features=3072, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (k_proj): SingularMoELinear(in_features=3072, out_features=1024, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (v_proj): SingularMoELinear(in_features=3072, out_features=1024, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (o_proj): SingularMoELinear(in_features=3072, out_features=3072, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "        )\n",
       "        (mlp): S2MoELlamaMLP(\n",
       "          (gate_proj): SingularMoELinear(in_features=3072, out_features=8192, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (up_proj): SingularMoELinear(in_features=3072, out_features=8192, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (down_proj): SingularMoELinear(in_features=8192, out_features=3072, num_experts=5, top_k=1, rank_of_router=16, )\n",
       "          (act_fn): SiLU()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm((3072,), eps=1e-05)\n",
       "        (post_attention_layernorm): LlamaRMSNorm((3072,), eps=1e-05)\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm((3072,), eps=1e-05)\n",
       "    (rotary_emb): LlamaRotaryEmbedding()\n",
       "  )\n",
       "  (lm_head): Linear(in_features=3072, out_features=128256, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with init_empty_weights():\n",
    "    model = S2MoELlamaForCausalLM(config)\n",
    "\n",
    "model.to_empty(device=\"cpu\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save_pretrained(\"outputs/s2_moe_llama\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        ...,\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.]], requires_grad=True)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.lm_head.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading checkpoint shards: 100%|██████████| 6/6 [00:00<00:00, 41.26it/s]\n"
     ]
    }
   ],
   "source": [
    "model = S2MoELlamaForCausalLM.from_pretrained(\"outputs/s2_moe_llama\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        ...,\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 0.,  ..., 0., 0., 0.]], requires_grad=True)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.lm_head.weight"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "s2_moe",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
